{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Visualizing MNIST + Summary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting data/train-images-idx3-ubyte.gz\n",
      "Extracting data/train-labels-idx1-ubyte.gz\n",
      "Extracting data/t10k-images-idx3-ubyte.gz\n",
      "Extracting data/t10k-labels-idx1-ubyte.gz\n",
      "Packages loaded\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import matplotlib.pyplot as plt\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "%matplotlib inline  \n",
    "mnist = input_data.read_data_sets('data/', one_hot=True)\n",
    "trainimg   = mnist.train.images\n",
    "trainlabel = mnist.train.labels\n",
    "testimg    = mnist.test.images\n",
    "testlabel  = mnist.test.labels\n",
    "print (\"Packages loaded\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Define networks\n",
    "## tf.variable_scope(\"NAME\"):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Parameters\n",
    "learning_rate   = 0.001\n",
    "training_epochs = 10\n",
    "batch_size      = 100\n",
    "display_step    = 2\n",
    "# Network Parameters\n",
    "n_input    = 784 # MNIST data input (img shape: 28*28)\n",
    "n_hidden_1 = 256 # 1st layer num features\n",
    "n_hidden_2 = 256 # 2nd layer num features\n",
    "n_hidden_3 = 256 # 3rd layer num features\n",
    "n_hidden_4 = 256 # 4th layer num features\n",
    "n_classes  = 10 # MNIST total classes (0-9 digits)\n",
    "\n",
    "# Store layers weight & bias\n",
    "stddev = 0.1\n",
    "with tf.variable_scope(\"MLP_WEIGHTS\"):\n",
    "    weights = {\n",
    "        'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1], stddev=stddev)),\n",
    "        'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], stddev=stddev)),\n",
    "        'h3': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_3], stddev=stddev)),\n",
    "        'h4': tf.Variable(tf.random_normal([n_hidden_3, n_hidden_4], stddev=stddev)),\n",
    "        'out': tf.Variable(tf.random_normal([n_hidden_4, n_classes], stddev=stddev))\n",
    "    }\n",
    "with tf.variable_scope(\"MLP_BIASES\"):\n",
    "    biases = {\n",
    "        'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n",
    "        'b2': tf.Variable(tf.random_normal([n_hidden_2])),\n",
    "        'b3': tf.Variable(tf.random_normal([n_hidden_3])),\n",
    "        'b4': tf.Variable(tf.random_normal([n_hidden_4])),\n",
    "        'out': tf.Variable(tf.random_normal([n_classes]))\n",
    "    }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Network ready\n"
     ]
    }
   ],
   "source": [
    "# Create model\n",
    "def multilayer_perceptron(_X, _weights, _biases, _keep_prob):\n",
    "    with tf.variable_scope(\"MLP_LAYER_1\"):\n",
    "        layer_1 = tf.nn.dropout(tf.nn.relu(tf.add(tf.matmul(_X, _weights['h1'])\n",
    "                                                  , _biases['b1'])), _keep_prob)\n",
    "    with tf.variable_scope(\"MLP_LAYER_2\"):\n",
    "        layer_2 = tf.nn.dropout(tf.nn.relu(tf.add(tf.matmul(layer_1, _weights['h2'])\n",
    "                                                  , _biases['b2'])), _keep_prob)\n",
    "    with tf.variable_scope(\"MLP_LAYER_3\"):\n",
    "        layer_3 = tf.nn.dropout(tf.nn.relu(tf.add(tf.matmul(layer_2, _weights['h3'])\n",
    "                                                  , _biases['b3'])), _keep_prob) \n",
    "    with tf.variable_scope(\"MLP_LAYER_OUT\"):\n",
    "        layer_4 = tf.nn.dropout(tf.nn.relu(tf.add(tf.matmul(layer_3, _weights['h4'])\n",
    "                                                  , _biases['b4'])), _keep_prob) \n",
    "    return (tf.matmul(layer_4, _weights['out']) + _biases['out'])\n",
    "print (\"Network ready\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Define functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Network Ready\n"
     ]
    }
   ],
   "source": [
    "# tf Graph input\n",
    "x = tf.placeholder(\"float\", [None, n_input], name=\"MLP_INPUT_x\")\n",
    "y = tf.placeholder(\"float\", [None, n_classes], name=\"MLP_TARGET_y\")\n",
    "keepratio = tf.placeholder(\"float\", name=\"MLP_DROPOUT\")\n",
    "# Construct model\n",
    "pred = multilayer_perceptron(x, weights, biases, keepratio)\n",
    "# Define loss and optimizer\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) # Softmax loss\n",
    "optm = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Adam Optimizer\n",
    "# Accuracy \n",
    "corr = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n",
    "accr = tf.reduce_mean(tf.cast(corr, \"float\"))\n",
    "# Initializing the variables\n",
    "init = tf.initialize_all_variables()\n",
    "print (\"Network Ready\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Summary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Summary ready\n"
     ]
    }
   ],
   "source": [
    "# Do some optimizations\n",
    "sess = tf.Session()\n",
    "sess.run(init)\n",
    "\n",
    "# Summary writer\n",
    "tf.scalar_summary('cross entropy', cost)\n",
    "tf.scalar_summary('accuracy', accr)\n",
    "merged = tf.merge_all_summaries()\n",
    "summary_writer = tf.train.SummaryWriter('/tmp/tf_logs/mlp_mnist'\n",
    "                                        , graph=sess.graph)\n",
    "print (\"Summary ready\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Start!\n",
      "Epoch: 000/010 cost: 0.475366192\n",
      " Training accuracy: 0.950\n",
      " Test accuracy: 0.929\n",
      "Epoch: 002/010 cost: 0.118928117\n",
      " Training accuracy: 0.970\n",
      " Test accuracy: 0.961\n",
      "Epoch: 004/010 cost: 0.073962761\n",
      " Training accuracy: 1.000\n",
      " Test accuracy: 0.973\n",
      "Epoch: 006/010 cost: 0.051166516\n",
      " Training accuracy: 0.980\n",
      " Test accuracy: 0.976\n",
      "Epoch: 008/010 cost: 0.038799497\n",
      " Training accuracy: 0.990\n",
      " Test accuracy: 0.980\n",
      "Optimization Finished!\n"
     ]
    }
   ],
   "source": [
    "print (\"Start!\")\n",
    "# Training cycle\n",
    "for epoch in range(training_epochs):\n",
    "    avg_cost = 0.\n",
    "    total_batch = int(mnist.train.num_examples/batch_size)\n",
    "    # Loop over all batches\n",
    "    for i in range(total_batch):\n",
    "        batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n",
    "        # Fit training using batch data\n",
    "        summary, _ = sess.run([merged, optm]\n",
    "                , feed_dict={x: batch_xs, y: batch_ys, keepratio: 0.7})\n",
    "        # Compute average loss\n",
    "        avg_cost += sess.run(cost\n",
    "                , feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/total_batch\n",
    "        # Add summary\n",
    "        summary_writer.add_summary(summary, epoch*total_batch+i)\n",
    "    # Display logs per epoch step\n",
    "    if epoch % display_step == 0:\n",
    "        print (\"Epoch: %03d/%03d cost: %.9f\" % (epoch, training_epochs, avg_cost))\n",
    "        train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})\n",
    "        print (\" Training accuracy: %.3f\" % (train_acc))\n",
    "        test_acc = sess.run(accr, feed_dict={x: testimg, y: testlabel, keepratio:1.})\n",
    "        print (\" Test accuracy: %.3f\" % (test_acc))\n",
    "        \n",
    "print (\"Optimization Finished!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### Run the command line\n",
    "##### tensorboard --logdir=/tmp/tf_logs/mlp_mnist\n",
    "### Open http://localhost:6006/ into your web browser"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/tsboard/mlp_mnist.png\">"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
